<?php
namespace App\Http\Controllers\Store;

use App\Models\ClientUserMessage;
use App\Models\ClientUserMessagesContent;
use App\Models\ClientUserMessagesType;
use App\Http\Requests\BasicRequest;
class MessageController extends CommonController {
    /**
     * @param BasicRequest $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 消息类型
     */
    public function messages_type(BasicRequest $request){

        $data = ClientUserMessagesType::where(['type'=>4])->select('id','name','image')->orderby('sort','desc')->get()->each(function($v,$k) {
            $v->unview_count = group99(ClientUserMessage::where(['uid'=>$this->uid,'type_id'=>$v->id,'viewed'=>0])->count());
            $latest = ClientUserMessage::select(['created_at','title','content_id'])->where(['uid'=>$this->uid,'type_id'=>$v->id])->latest()->first();

            if($latest->content_id>0){
                $content=ClientUserMessagesContent::where(['id'=>$latest->content_id])->first();
                $v->preview=$content->title;
            }else {
                $v->preview = $latest->title;
            }
            $v->preview_time = date($latest->created_at);
        });
        return json_success('OK',$data);
    }

    // 某一消息类型下的消息列表
    public function messages_list(BasicRequest $request){
        $type_id = $request->input('type_id');
        $uid = $this->uid;
        $data = ClientUserMessage::where(['type_id'=>$type_id,'uid'=>$uid])->select('content_id','created_at','content_id','title','content','viewed','id')->latest()->pages()->each(function($v,$k){
            if($v->content_id>0){
                $content=ClientUserMessagesContent::where(['id'=>$v->content_id])->first();
                $v->content=$content->content;
                $v->title=$content->title;
            }
        });
        // 设置为已读
        ClientUserMessage::where(['type_id'=>$type_id])->update(['viewed'=>1]);
        return json_success('OK',$data);
    }

    // 消息详情
    public function messages_detail(BasicRequest $request){
        $id = $request->input('id');
        $data = ClientUserMessage::find($id);
        if($data->content_id>0){
            $content=ClientUserMessagesContent::where(['id'=>$data->content_id])->first();
            $data->content=$content->content;
            $data->title=$content->title;
        }
        return json_success('OK',$data);
    }
}